package com.seo.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.seo.pojo.ReturnBody;
import com.seo.service.user.sdk.ConfigService;
import com.seo.service.user.sdk.UserService;

import lombok.extern.slf4j.Slf4j;

/**
 * DomainSecurityInterceptor
 * 
 * @author shibeilei
 * @version 2017.11.30 12:20
 */
@Slf4j
public class DomainSecurityInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private UserService userService;

	@Autowired
	private ConfigService configService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		log.info("进入域名拦截器...");
		String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getServletPath();
		log.info("当前访问地址[{}]", url);
		String domain = request.getServerName();
		log.info("当前访问域名[{}]", domain);

		String seoDomain = configService.getConfig("domain");

		if (StringUtils.equals(domain, seoDomain)) {
			request.setAttribute("companyName", "金发仁");
			request.setAttribute("companyDesc", "金发仁");
			request.setAttribute("domainUserId", 0);
			return true;
		}

		ReturnBody body = ReturnBody.init();
		body.run(userService.getCheckUserByDomain(domain));
		if (!body.isSuccess()) {
			response.setStatus(400);
			return false;
		}
		Map<String, Object> user = body.get("user", String.class, Object.class);
		String roleCode = (String) user.get("roleCode");
		String companyName = null;
		String companyDesc = null;
		if ("proxy".equals(roleCode)) {
			companyName = (String) user.get("companyName");
			companyDesc = (String) user.get("companyDesc");
		}
		request.setAttribute("companyName", StringUtils.isEmpty(companyName) ? "" : companyName);
		request.setAttribute("companyDesc", StringUtils.isEmpty(companyDesc) ? "" : companyDesc);

		request.setAttribute("domainUserId", user.get("id"));
		return true;
	}

}
